package com.easy.neo4j.repository;

import com.easy.neo4j.entry.Park;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ParkRepository extends Neo4jRepository<Park, Long> {
    @Query("MATCH (n1:Park) " +
            "WITH n1,point({latitude:toFloat(n1.lat) , longitude:toFloat(n1.lng)}) AS parkPoint, " +
            "     point({latitude:toFloat($lat),longitude:toFloat($lng)}) AS inputPoint " +
            "WITH n1, point.distance(parkPoint,inputPoint) AS Distance " +
            "WHERE Distance < toFloat($lmt) " +
            "RETURN n1")
    List<Park> findAllPark(@Param("lat") String lat, @Param("lng") String lng, @Param("lmt") String lmt);

    @Query("MATCH(n1:Park) WHERE n1.name CONTAINS $address AND n1.c_citycode CONTAINS $cityCode RETURN n1 SKIP $skipnum LIMIT $limit ")
    List<Park> findAllParkByCityCode(@Param("address") String address, @Param("cityCode") String cityCode, @Param("skipnum") Integer skipnum, @Param("limit") Integer limit);


    @Query("MATCH(n1:Park) WHERE n1.name CONTAINS $address AND n1.c_citycode CONTAINS $cityCode RETURN count(n1)")
    Integer getParkCount(@Param("address") String address, @Param("cityCode") String cityCode);

    @Query("MATCH (n:Park {name:$parkName}) SET n.lat = $lat,n.lng = $lng ")
    void updateParkPointByName(@Param("parkName") String parkName, @Param("lat") String lat, @Param("lng") String lng);

    @Query("CREATE(n:Park {address:$address,bikeNum:'0',c_citycode:$cityCode,c_regionId:$reginId,lat:$lat,lng:$lng,level:'0',name:$name})")
    void addPark(@Param("address") String address, @Param("cityCode") String cityCode, @Param("reginId") String reginId, @Param("lat") String lat, @Param("lng") String lng, @Param("name") String parkName);

    @Query("MATCH (n:Park {address:$address}) " +
            "MATCH (p:Park) " +
            "WHERE n <> p " +
            "AND distance(point({latitude: n.lat, longitude: n.lng}), point({latitude: p.lat, longitude: p.lng})) <= 500 " +
            "CREATE (n)-[:NEARBY]->(p), (p)-[:NEARBY]->(n) ")
    void createNearbyRelationships(@Param("address") String address);
}
